package com.itheima.ydd.service.impl;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.itheima.ydd.dto.AdvposPage;
import com.itheima.ydd.dto.SysUserDto;
import com.itheima.ydd.entity.Result;
import com.itheima.ydd.entity.SysRole;
import com.itheima.ydd.entity.SysUser;
import com.itheima.ydd.mapper.SysUserMapper;
import com.itheima.ydd.service.SysRoleService;
import com.itheima.ydd.service.SysUserService;
import com.itheima.ydd.utils.TextTransUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.ObjectUtils;
import org.springframework.util.StringUtils;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * @author Wang.XL
 */
@Service
@Slf4j
public class SysUserServiceImpl extends ServiceImpl<SysUserMapper, SysUser> implements SysUserService {

    @Autowired
    private SysRoleService roleService;

    /**
     * 用户列表-分页
     *
     * @param loginName
     * @param status
     * @param phone
     * @param page
     * @param limit
     * @return
     */
    @Override
    public AdvposPage findList(String loginName, String status, String phone, String page, String limit) {
        //1.设置分页参数
        Page<SysUser> sysUserPage = new Page<SysUser>(Integer.parseInt(page), Integer.parseInt(limit));
        Page<SysUserDto> sysUserDtoPage = new Page<SysUserDto>(Integer.parseInt(page), Integer.parseInt(limit));

        //2.设置模糊查询条件
        LambdaQueryWrapper<SysUser> wrapper = new LambdaQueryWrapper<>();
        wrapper.like(StringUtils.hasText(loginName), SysUser::getLogin_name, loginName)
                .eq(StringUtils.hasText(status), SysUser::getPhone, status)
                .like(StringUtils.hasText(phone), SysUser::getPhone, phone)
                .orderByDesc(SysUser::getUpdate_date);

        this.page(sysUserPage, wrapper);
        BeanUtils.copyProperties(sysUserPage, sysUserDtoPage, "records");

        //3.获取sysUserPage中的records
        List<SysUser> sysUserList = sysUserPage.getRecords();
        List<SysUserDto> sysUserDtoList = new ArrayList<>();
        for (SysUser sysUser : sysUserList) {
            List<String> rolenames = new ArrayList<>();

            //将对象sysuser招工难所有的数据赋值给dto
            SysUserDto userDto = new SysUserDto();
            BeanUtils.copyProperties(sysUser, userDto, "roleId");
            //使用id去查
            //转换为集合
            List<String> roleIds = TextTransUtil.doStringToArray(sysUser.getRoleId());
            userDto.setRole_id(roleIds);
            //遍历集合拿到role表中的角色名称
            for (String id : roleIds) {
               SysRole sysRole = roleService.getById(id);
                if (!ObjectUtils.isEmpty(sysRole)){
                    rolenames.add(sysRole.getName());
                }
            }
            userDto.setRolename(rolenames);
            sysUserDtoList.add(userDto);
        }
        //4.将角色赋值到记录中
        sysUserDtoPage.setRecords(sysUserDtoList);
        AdvposPage advposPage = new AdvposPage();
        advposPage.setCount( (int)sysUserDtoPage.getTotal());
        advposPage.setCurrentPage((int) sysUserDtoPage.getCurrent());
        advposPage.setPageSize((int) sysUserDtoPage.getSize());
        advposPage.setTotalPages((int) sysUserDtoPage.getPages());
        advposPage.setData(sysUserDtoPage.getRecords());
        return advposPage;
    }

    /**
     * 根据id进行删除数据
     *
     * @param id
     */
    @Override
    @Transactional
    public Result delSysUser(String id) {
        //1.获取得到的对象
        LambdaQueryWrapper<SysUser> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(SysUser::getId, id);
        SysUser sysUser = this.getById(id);
        //2.判断状态-启用状态不能删除
        if (sysUser.getStatus() == 1) {
            return new Result(402, "启用状态不能删除");
        }
        //3.自己不能删除自己

        //4.管理员可以删除全部,普通人不能删除管理员
        //4.1获取删除的用户是不是管理员
        String roleId = sysUser.getRoleId();
        List<String> list = TextTransUtil.doStringToArray(roleId);
        String name = roleService.getById(list.get(0)).getName();
        System.out.println("nama:"+name);
        if ("超级管理员".equals(name)) {
            return new Result(401, "对不起您没有权限删除管理员");
        }
        boolean falg = this.removeById(id);
        return new Result(0, falg?"删除成功":"删除失败");
    }

    /**
     * 管理员添加
     *
     * @param map
     * @return
     */
    @Override
    @Transactional
    public Result addSysUser(Map<String, Object> map) {
        String jsonString = JSON.toJSONString(map);
        SysUser sysUser = JSON.parseObject(jsonString,SysUser.class);
        String roleId = map.get("role_id").toString();
        roleId = TextTransUtil.doArrayToString(roleId);
        sysUser.setRoleId(roleId);
        //1.利用login_name或者phone或者email去查询后台
        LambdaQueryWrapper<SysUser> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(SysUser::getLogin_name, sysUser.getLogin_name())
                .or()
                .eq(SysUser::getPhone, sysUser.getPhone())
                .or()
                .eq(SysUser::getEmail, sysUser.getEmail());
        SysUser user = this.getOne(wrapper);
        //2.如果有就返回添加失败,并提醒用户已经存在
        if (!ObjectUtils.isEmpty(user))
            return new Result(403, "用户已经存在,请保证手机号,账号,邮件唯一");
        //3.如果没有就去进行添加,并返回成功
        boolean falg = this.save(sysUser);
        return new Result(0, falg ? "添加成功" : "添加失败");
    }

    /**
     * 管理员更改
     *
     * @param map
     * @return
     */
    @Override
    public Result updataSysUser(Map<String, Object> map) {
        String jsonString = JSON.toJSONString(map);
        SysUser sysUser = JSON.parseObject(jsonString,SysUser.class);
        String roleId = map.get("role_id").toString();
        roleId = TextTransUtil.doArrayToString(roleId);
        sysUser.setRoleId(roleId);//设置查询条件
        LambdaQueryWrapper<SysUser> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(SysUser::getId, sysUser.getId());
        SysUser user = this.getOne(wrapper);
//        if ("1".equals(user.getId())) {
//            //查询得到的用户是不是管理员,如果是管理员,不能修改
//            return new Result(405, "您的权限不够");
//        }
        boolean update = this.update(sysUser, wrapper);
        return new Result(0, update ? "修改成功" : "修改失败");
    }
}